package v1

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	bc "application/blockchain"
	"application/pkg/app"
)

type CreditRequestBody struct {
	Name   string `json:"name"`   //用户姓名
	Code   string `json:"code"`   //身份证号
	IsLock string `json:"isLock"` //是否有不良记录 true有 false无
}

type CheckCreditRequestBody struct {
	Name string `json:"name"` //用户姓名
	Code string `json:"code"` //身份证号
}

func AddCredit(c *gin.Context) {

	appG := app.Gin{C: c}
	body := new(CreditRequestBody)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}

	var bodyBytes [][]byte

	bodyBytes = append(bodyBytes, []byte(body.Name), []byte(body.Code), []byte(body.IsLock))

	//调用智能合约
	resp, err := bc.ChannelExecute("addCredit", bodyBytes)
	if err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}

	appG.Response(http.StatusOK, "成功", resp.Payload)
}

func CheckCredit(c *gin.Context) {

	appG := app.Gin{C: c}
	body := new(CheckCreditRequestBody)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}

	var bodyBytes [][]byte

	bodyBytes = append(bodyBytes, []byte(body.Name), []byte(body.Code))

	//调用智能合约
	resp, err := bc.ChannelQuery("checkCredit", bodyBytes)
	if err != nil {
		appG.Response(http.StatusInternalServerError, "失败", err.Error())
		return
	}
	var r []interface{}
	err = json.Unmarshal(resp.Payload, &r)
	if err != nil {
		appG.Response(http.StatusInternalServerError, "json解析失败", err.Error())
		return
	}

	appG.Response(http.StatusOK, "成功", r)
}
